from django.shortcuts import render
from django.views import View
from django.db.models import ObjectDoesNotExist
from django import http
from django.core.paginator import Paginator, EmptyPage
from django.utils import timezone
from datetime import datetime

from goods.models import GoodsCategory, SKU, GoodsVisitCount
from contents.utils import get_categories
from goods.utils import get_breadcrumb
from goods import contants
from utils.response_code import RETCODE


# Create your views here.
class GoodsVisitCountView(View):
    def post(self, request, category_id):
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except ObjectDoesNotExist:
            return http.HttpResponseForbidden('The category id is not exist')

        tm = timezone.localtime()
        tm_str = '%d-%02d-%02d' % (tm.year, tm.month, tm.day)
        tm_obj = datetime.strptime(tm_str, '%Y-%m-%d')

        try:
            visit_record = GoodsVisitCount.objects.get(category_id=category_id, date=tm_obj)
        except GoodsVisitCount.DoesNotExist:
            # visit_record = GoodsVisitCount.objects.create(category=category, date=tm_obj)
            visit_record = GoodsVisitCount()

        visit_record.category = category
        visit_record.date = tm_obj
        visit_record.count += 1

        try:
            visit_record.save()
        except Exception as e:
            return http.HttpResponseForbidden('Create visit record failure')

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class GoodsDetailView(View):
    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except ObjectDoesNotExist:
            return render(request, '404.html')

        categories = get_categories()
        breadcrumb = get_breadcrumb(sku.category)

        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for sku_spec in sku_specs:
            sku_key.append(sku_spec.option.id)

        skus = sku.spu.sku_set.all()
        skus_options_id_map = {}

        for s in skus:
            s_key = []
            s_specs = s.specs.order_by('spec_id')
            for s_spec in s_specs:
                s_key.append(s_spec.option.id)
            skus_options_id_map[tuple(s_key)] = s.id

        spu_specs = sku.spu.specs.order_by('id')

        for index, spu_spec in enumerate(spu_specs):
            key = sku_key[:]
            spu_spec_options = spu_spec.options.order_by('id')
            for option in spu_spec_options:
                key[index] = option.id
                option.sku_id = skus_options_id_map.get(tuple(key))
            spu_spec.spec_options = spu_spec_options

        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'spu_specs': spu_specs
        }

        return render(request, 'detail.html', context)


class HotGoodsViews(View):
    def get(self, request, category_id):
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]

        hot_skus = []
        for sku in skus:
            sku_dict = {
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            }

            hot_skus.append(sku_dict)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'hot_skus': hot_skus})


class ListView(View):
    def get(self, request, category_id, page_num):
        try:
           category = GoodsCategory.objects.get(id=category_id)
        except ObjectDoesNotExist:
            return http.HttpResponseForbidden('Incorrect category_id')

        categories = get_categories()
        breadcrumb = get_breadcrumb(category)

        sort = request.GET.get('sort', 'default')
        if sort == 'price':
            sort_filed = sort
        elif sort == 'hot':
            sort_filed = '-sales'
        else:
            sort = 'default'
            sort_filed = 'create_time'

        try:
            goods_skus = category.sku_set.filter(is_launched=True).order_by(sort_filed)
        except ObjectDoesNotExist:
            return http.HttpResponseNotFound('404')

        page_skus = Paginator(goods_skus, contants.NUM_OF_PER_PAGE)

        try:
            skus = page_skus.page(page_num)
        except EmptyPage:
            return http.HttpResponseNotFound('404')

        total_page = page_skus.num_pages

        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'skus': skus,
            'total_page': total_page,
            'page_num': page_num,
            'sort': sort,
            'category_id': category_id
        }

        return render(request, 'list.html', context)


